package com.alex.demo.service;

import com.alex.demo.lock.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisLockService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient client;

    public String redisLock() {
        try (RedisLock redisLock = new RedisLock(redisTemplate, "redisKey", 30)) {
            // 如果成功获取锁
            if (redisLock.lock()) {
                // 执行业务代码
                Thread.sleep(15000);
                return "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 没获取到锁,返回失败
        return "fail";
    }

    public String redissionLock() {
        RLock rLock = client.getLock("order");
        rLock.lock(30, TimeUnit.SECONDS);
        log.info("我获取到了锁！！！");
        try {
            Thread.sleep(10000);
            return "success";
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            log.info("我释放了锁！！！");
            rLock.unlock();
        }
        return "fail";
    }
}
